// 微信common api
import {bindUser} from '../http/protocol'
import {appkey} from '../const/common'
// const app = getApp();
// 获取登陆code
export const getLogin = () => new Promise((resolve, reject) => {
  wx.login({
    success: res => {
      if(res.errMsg === 'login:ok') {
        resolve(res.code)
      }
    },
    fail: res => {
      reject(500)
    }
  })
})

// 检查微信登陆态
export const checkLogin = () => new Promise((resolve, reject) => {
  wx.checkSession({
    success: (res) =>{
      //session_key 未过期，并且在本生命周期一直有效
      resolve(true)
      
    },
    fail :(res) =>{
      resolve(false)
    }
  })
})

// 检查用户授权信息
export const getSetting = (info="scope.userInfo") => new Promise((resolve, reject) => {
  wx.getSetting({
    success: res => {
      let {authSetting} = res;
      resolve(authSetting[info])
    }
  })
})

// 获取用户信息
export const getUserInfo = () => new Promise((resolve, reject) => {
  wx.getUserInfo({
    success:(res) => {
      resolve(res)
    }
  })
})

// 无痛更新membercode 在登陆态失效的时候
export const updatecode = (callback) => new Promise(async (resolve, reject) => {
  // 假设用户已经授权了获取用户信息
  let code = await getLogin();
  let userInfo1 = await getUserInfo();
  let {encryptedData,rawData,signature,iv,errMsg,userInfo} = userInfo1;
  let res = await bindUser({
    appkey,
    code,
    data: JSON.stringify({
      encryptedData,rawData,signature,iv
    })
  });

  if(res.success) {
    let data = res.data;
    let {memberEncode,bindMobile} = data;
  console.log('memberEncode111',memberEncode)

    wx.setStorageSync('memberEncode', memberEncode); //把信息存入缓存
    wx.setStorageSync('bindMobile', bindMobile); //把信息存入缓存
    callback && callback()

  } else {
    wx.showToast({
      title: res.errMsg,
      icon: 'none'
    })
  }


})